package com.sanji.sjmallmodule.phoneshell;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.order.ShopcarChildBean;
import com.sanji.sjmallmodule.order.ShopcarGroupBean;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 定制购物车
 * Created by ZSF on 17/9/12.
 */

public class ShellShopCarActivity extends BaseActivity implements View.OnClickListener, NoHttpListener,ShellShopCarAdapter.CBoxCheckListener {

    @BindView(R.id.common_back_img)
    ImageView backImg;
    @BindView(R.id.common_title_tv)
    TextView titleTv;
    @BindView(R.id.shell_shopcar_all_cb_layout)
    LinearLayout allCbLayout;
    @BindView(R.id.shell_shopcar_title_cb)
    CheckBox allCbox;
    @BindView(R.id.shell_shopcar_list_view)
    ListView listView;
    @BindView(R.id.shell_shopcar_bom_all_layout)
    LinearLayout bomLayout;
    @BindView(R.id.shell_shopcar_all_cb)
    CheckBox bomAllCb;
    @BindView(R.id.shell_shopcar_coust_tv)
    TextView coustTv;
    @BindView(R.id.shell_shopcar_submi_btn)
    TextView submitTv;
    @BindView(R.id.shell_shopcar_null_linear)
    LinearLayout nullLayout;

    private ShellShopCarAdapter shopCarAdapter;
    private List<ShellCartBean> cartList = new ArrayList<>();
    private String cartUrl="";
    private String uid;
    private Request<JSONObject> cartRequest;
    private int deltPos;
    private String deltOrderUrl="";
    private Request<JSONObject> deltRequest;
    private int editKKMovePos;
    //结算订单id
    private List<String> ids = new ArrayList<>();
    private String orderIds;
    private String tpUrl="";
    private Request<JSONObject> tpRequest;
    //重做
    private String orderRdUrl = "";
    private String rdKmoveId = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shell_shop_car);
        ButterKnife.bind(this);
        initViews();
        getData();
    }

    private void initViews() {
        backImg.setOnClickListener(this);
        titleTv.setText("定制购物车");
        allCbox.setOnClickListener(this);
        bomAllCb.setOnClickListener(this);
        submitTv.setOnClickListener(this);

        uid = myShare.getString(ConfigConts.USER_ID, "");

//
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_back_img:
                finishActivity();
                break;
            case R.id.shell_shopcar_title_cb:
                if (cartList.size()>0){
                    boolean flag = allCbox.isChecked();
                    for (ShellCartBean cart : cartList) {
                        cart.setSelected(flag);
                        String id = cart.getId();
                        if (!ids.contains(id)){
                            ids.add(id);
                        }
                    }
                    bomAllCb.setChecked(flag);
                    shopCarAdapter.notify(cartList);
                    if (!flag){
                        ids.clear();
                    }
                }
                break;
            case R.id.shell_shopcar_all_cb:
                if (cartList.size()>0){
                    boolean flag = bomAllCb.isChecked();
                    for (ShellCartBean cart : cartList) {
                        cart.setSelected(flag);
                        String id = cart.getId();
                        if (!ids.contains(id)){
                            ids.add(id);
                        }
                    }
                    allCbox.setChecked(flag);
                    shopCarAdapter.notify(cartList);
                    if (!flag){
                        ids.clear();
                    }
                }
                break;
            case R.id.shell_shopcar_submi_btn:
                //结算
                if (ids.size()>0){
                    StringBuffer strBuff = new StringBuffer();
                    for (String id:ids){
                        strBuff.append(id).append(",");
                    }
                    orderIds = strBuff.substring(0,strBuff.length()-1).toString();
                    tpUrl = ConfigAPI.PHONE_SHELL_ORDER_TOPAY + orderIds;
                    tpRequest = NoHttp.createJsonObjectRequest(tpUrl,RequestMethod.GET);
                    tpRequest.addHeader("X-Authorization-MemberId",uid);
                    tpRequest.setCancelSign(tpUrl.hashCode());
                    NoHttpCallBack.getInstance().add(mCtx, tpUrl.hashCode(), tpRequest, this, true, true);


                }else{
                    Tools.toastTools(mCtx,"选几件商品吧");
                }
                break;
        }
    }

    private void getData() {
        cartUrl = ConfigAPI.PHONE_SHELL_GET_CART;
        cartRequest = NoHttp.createJsonObjectRequest(cartUrl, RequestMethod.GET);
        cartRequest.setCancelSign(cartUrl.hashCode());
        cartRequest.addHeader("X-Authorization-MemberId", uid);
        NoHttpCallBack.getInstance().add(mCtx, cartUrl.hashCode(), cartRequest, this, true, true);
    }

    @Override
    public void onSuccessed(int what, Response response) {
        int requestCode = response.responseCode();
        if (requestCode == 200) {
            if (what == cartUrl.hashCode()) {
                JSONObject jsonObject = (JSONObject) response.get();
                if (jsonObject != null) {
                    JSONArray orders = jsonObject.optJSONArray("orders");
                    if (orders != null && orders.length() > 0) {
                        //有数据
                        int size = orders.length();
                        ShellCartBean cart = null;
                        JSONObject obj = null;
                        JSONObject order = null;
                        for (int i = 0; i < size; i++) {
                            obj = orders.optJSONObject(i);
                            cart = new ShellCartBean();
                            cart.setCategoryName(obj.optString("categoryName"));
                            cart.setTitle(obj.optString("title"));
                            cart.setKkmoveUrl(obj.optString("kkmoveUrl"));
                            cart.setShowView(obj.optString("showView"));
                            order = obj.optJSONObject("order");
                            cart.setId(order.optString("id"));
                            cart.setKkmoveId(order.optString("kkmoveId"));
                            cart.setQuantity(order.optInt("quantity"));
                            cart.setGoodsId(order.optString("goodsId"));
                            cart.setPrice(order.optDouble("price"));
                            cart.setSalePrice(order.optDouble("salePrice"));
                            cart.setRetailPrice(order.optDouble("retailPrice"));
                            cart.setUsername(order.optString("username"));
                            cart.setUserMobile(order.optString("userMobile"));
                            cart.setStatus(order.optString("status"));
                            cart.setAmount(order.optDouble("amount"));
                            cart.setOrderNum(order.optString("orderNum"));
                            cart.setCreateTime(order.optString("createTime"));
                            cart.setCarriage(order.optInt("carriage"));
                            cart.setGyResult(order.optString("gyResult"));
                            cart.setMemberId(order.optString("memberId"));
                            cart.setSignForTime(order.optString("signForTime"));
                            cart.setPayNum(order.optString("payNum"));
                            cartList.add(cart);
                        }

                        if (shopCarAdapter == null) {
                            shopCarAdapter = new ShellShopCarAdapter(this,cartList);
                            listView.setAdapter(shopCarAdapter);
                            shopCarAdapter.setCBoxCheckListener(this);
                        }else{
                            shopCarAdapter.notify(cartList);
                        }
                    }

                }
            }else if(what == deltOrderUrl.hashCode()){
                JSONObject jsonObject = (JSONObject) response.get();
                String status = jsonObject.optString("status");
                if (ConfigConts.STATUS_SUCCESS.equals(status)){
                    Tools.toastTools(mCtx,"删除成功");
                    cartList.remove(deltPos);
                    shopCarAdapter.notify(cartList);
                }
            }else if(what == tpUrl.hashCode()){
                JSONObject jsonObject = (JSONObject) response.get();
                String status = jsonObject.optString("status");
                if (status.equals(ConfigConts.STATUS_SUCCESS)){
                    JSONObject result = jsonObject.optJSONObject("result");
                    double amount = result.optDouble("amount");
                    String payNum = result.optString("payNumber");

                    intent = new Intent(mCtx,ShellPayActivity.class);
                    intent.putExtra("amount",amount);
                    intent.putExtra("payNum",payNum);
                    intent.putExtra("ids",orderIds);
                    startActivityForResult(intent,ConfigConts.ACTION_ALIPAY_REFRESH);

                }
            }else if(what == orderRdUrl.hashCode()){
                JSONObject obj = (JSONObject) response.get();
                String status = obj.optString("status");
                if (status.equals(ConfigConts.STATUS_SUCCESS)){
                    ShellCartBean cart = cartList.get(editKKMovePos);
                    String oldKmId = cart.getKkmoveId();
                    cart.setKkmoveId(rdKmoveId);
                    String showUrl = "http://www.kkmove.com/appadmin/designview/" + rdKmoveId;
                    cart.setShowView(showUrl);
                    String kkmoveUrl = cart.getKkmoveUrl();
                    kkmoveUrl = kkmoveUrl.replace(oldKmId,rdKmoveId);
                    cart.setKkmoveUrl(kkmoveUrl);

                    //刷新adapter中item
                    shopCarAdapter.updateItemView(listView,editKKMovePos,showUrl);


                }else{
                    Tools.toastTools(mCtx,"重做失败，请重试");
                }
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(mCtx, "连接超时！");
    }

    @Override
    public void cbCheck(int pos) {
        ShellCartBean cartBean = cartList.get(pos);
        if (cartBean.isSelected()){
            ids.add(cartBean.getId());
        }else{
            ids.remove(cartBean.getId());
        }

        //控制外围cbox
        boolean allCheck = true;
        for (ShellCartBean cart : cartList){
            if (!cart.isSelected()) {
                allCheck = false;
                break;
            }
        }
        allCbox.setChecked(allCheck);
        bomAllCb.setChecked(allCheck);
    }

    @Override
    public void deltItem(int pos) {
        deltPos = pos;
        ShellCartBean cart = cartList.get(pos);

        deltOrder(cart.getId());
    }

    @Override
    public void editKKMove(int pos) {
        editKKMovePos = pos;
        ShellCartBean cart = cartList.get(pos);

        intent = new Intent(mCtx,ShellWebViewActivity.class);
        intent.putExtra("webType",1);
        intent.putExtra("kkmoveUrl",cart.getKkmoveUrl());
        startActivityForResult(intent,ConfigConts.ACTION_SHELL_CART_EDIT);

    }

    private void deltOrder(String orderId){
        deltOrderUrl = ConfigAPI.PHONE_SHELL_DELT_ORDER + orderId;
        deltRequest = NoHttp.createJsonObjectRequest(deltOrderUrl,RequestMethod.GET);
        deltRequest.setCancelSign(deltOrderUrl.hashCode());
        NoHttpCallBack.getInstance().add(this, deltOrderUrl.hashCode(), deltRequest, this, true, true);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case ConfigConts.ACTION_SHELL_CART_EDIT:
                    ShellCartBean cart = cartList.get(editKKMovePos);
                    rdKmoveId = data.getStringExtra("kkmoveId");
                    if (!rdKmoveId.equals(cart.getKkmoveId())){
                        //重做
                        orderRedo(cart.getOrderNum(),rdKmoveId);
                    }
                    break;
                case ConfigConts.ACTION_ALIPAY_REFRESH:
                    getData();
                    break;
            }
        }
    }


    private void orderRedo(String orderNum,String kmId){
        orderRdUrl = ConfigAPI.PHONE_SHELL_ORDER_REDO + orderNum + "&kkmoveId="+kmId;
        Request<JSONObject> rdRequest = NoHttp.createJsonObjectRequest(orderRdUrl, RequestMethod.POST);
        rdRequest.setCancelSign(orderRdUrl.hashCode());
        NoHttpCallBack.getInstance().add(mCtx, orderRdUrl.hashCode(), rdRequest, this, true, true);

    }
}
